import Rotuer from 'koa-router';

export const routerParser = (methods, prefix = "") => {
  const router = new Rotuer({
    prefix
  });
  for (let key in methods) {
    const arr = key.split(" ");
    let method, url;
    if (arr.length > 1) {
      method = arr[0];
      url = arr[1];
    } else if (arr.length === 1) {
      // 请求是GET
      method = "GET";
      url = arr[0];
    } else {
      throw new Error(`参数异常,` + key.toString());
    }
    if (typeof methods[key] === 'function') {
      router[method.toLocaleLowerCase()](url, methods[key]);
    } else if (typeof methods[key] === 'object') {
      router[method.toLocaleLowerCase()](url, () => methods[key]);
    } else {
      throw new Error(`不支持的类型,` + typeof methods[key]);
    }
  }
  return router;
}

export default routerParser;
